#!/bin/bash
# xtrabackup 快速恢复脚本，适配 MySQL 5.7/8.0
# 自动合并全量+增量链，一键还原到目标 datadir

# ============ 参数区 ============
# 备份目录（需与备份脚本一致）
BACKUP_DIR="/data/mysql_backup"
# 目标数据目录（MySQL datadir，恢复到此目录）
RESTORE_DATADIR="/data/mysql_data_restore"
# xtrabackup 可执行文件路径
XTRABACKUP_BIN="xtrabackup"
# 日志文件
LOG_FILE="$BACKUP_DIR/xtrabackup_restore.log"

# ============ 函数区 ============
log() {
  echo "[$(date '+%F %T')] $1" | tee -a "$LOG_FILE"
}

# 检查并准备目录
if [[ ! -d "$BACKUP_DIR" ]]; then
  log "备份目录不存在: $BACKUP_DIR"; exit 1
fi
mkdir -p "$RESTORE_DATADIR"

# 查找最新全量备份
FULL_BACKUP=$(ls -dt $BACKUP_DIR/full_* 2>/dev/null | head -1)
if [[ -z "$FULL_BACKUP" ]]; then
  log "未找到全量备份，无法恢复！"; exit 1
fi
log "找到最新全量备份: $FULL_BACKUP"

# 查找对应增量链
INC_LIST=()
LAST_DIR="$FULL_BACKUP"
while true; do
  NEXT_INC=$(ls -dt $BACKUP_DIR/inc_* 2>/dev/null | grep -A9999 "$(basename $LAST_DIR | sed 's/full_/inc_/')" | grep -v "$(basename $LAST_DIR)" | head -1)
  if [[ -z "$NEXT_INC" ]]; then
    break
  fi
  INC_LIST+=("$NEXT_INC")
  LAST_DIR="$NEXT_INC"
done

# 合并全量和所有增量
log "开始 prepare 合并全量备份..."
$XTRABACKUP_BIN --prepare --apply-log-only --target-dir=$FULL_BACKUP &>> $LOG_FILE
for INC in "${INC_LIST[@]}"; do
  log "合并增量: $INC 到 $FULL_BACKUP"
  $XTRABACKUP_BIN --prepare --apply-log-only --target-dir=$FULL_BACKUP --incremental-dir=$INC &>> $LOG_FILE
  if [[ $? -ne 0 ]]; then
    log "合并增量失败: $INC"; exit 1
  fi
done
log "合并完成，准备恢复文件..."

# 恢复到目标 datadir
$XTRABACKUP_BIN --copy-back --target-dir=$FULL_BACKUP --datadir=$RESTORE_DATADIR &>> $LOG_FILE
if [[ $? -eq 0 ]]; then
  log "恢复文件已复制到 $RESTORE_DATADIR"
else
  log "恢复文件复制失败！"; exit 1
fi

# 修改权限（需根据实际 MySQL 运行用户调整）
chown -R mysql:mysql $RESTORE_DATADIR
log "已修改 $RESTORE_DATADIR 权限为 mysql:mysql"

log "恢复完成！请确保 MySQL 关闭后再替换 datadir，或用新实例启动。"
exit 0
